<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>权限管理</title>
    <link rel="stylesheet" th:href="@{/css/admin/base.css}">
    <link rel="stylesheet" th:href="@{/lib/flatpickr/flatpickr.min.css}">
    <link rel="stylesheet" th:href="@{/css/admin/app.css}">
    <link rel="stylesheet" th:href="@{/lib/tree/zTreeStyle.css}" type="text/css">

</head>

<body class="page-device">
<div class="app-page">
    <div class="app-page-header">
        <div class="page-title">
            <div class="title">权限资源</div>
        </div>
    </div>

    <div class="app-page-content">

        <div class="app-card">
            <div class="app-card-body z-df">
                <!-- 左侧 -->
                <div class="left-sidebar">
                    <div class="body">
                        <ul id="tree" class="ztree"></ul>
                    </div>
                </div>
                <!-- 列表数据 -->
                <div class="z-table-con z-hide" data-checkAuth>
                    <form>
                        <div class="form-item row">
                            <div class="label">
                                <label>父级权限ID</label>
                            </div>
                            <div class="body">
                                <p class="parentId" name="parentId"></p>
                            </div>
                        </div>
                        <div class="form-item row">
                            <div class="label">
                                <label>权限ID</label>
                            </div>
                            <div class="body">
                                <p class="authorityId" name="authorityId"></p>
                            </div>
                        </div>
                        <div class="form-item row">
                            <div class="label">
                                <label>权限名称</label>
                            </div>
                            <div class="body">
                                <p class="authorityName" name="authorityName"></p>
                            </div>
                        </div>

                        <div class="form-item row">
                            <div class="label">
                                <label>类型</label>
                            </div>
                            <div class="body">
                                <p class="type" name="type"></p>
                            </div>
                        </div>
                        <div class="form-item row">
                            <div class="label">
                                <label>权限描述</label>
                            </div>
                            <div class="body">
                                <p class="authorityDesc" name="authorityDesc"></p>
                            </div>
                        </div>

                        <div class="form-item row">
                            <div class="label">
                                <label>权限标识</label>
                            </div>
                            <div class="body">
                                <p class="sign" name="sign"></p>
                            </div>
                        </div>
                        <div class="form-item row">
                            <div class="label">
                                <label>权限路径</label>
                            </div>
                            <div class="body">
                                <p class="url" name="url"></p>
                            </div>
                        </div>
                        <div class="form-item row">
                            <div class="label">
                                <label>按钮CLASS</label>
                            </div>
                            <div class="body">
                                <p class="classes" name="classes"></p>
                            </div>
                        </div>
                        <div class="form-item row">
                            <div class="label">
                                <label>按钮ID</label>
                            </div>
                            <div class="body">
                                <p class="itemId" name="itemId"></p>
                            </div>
                        </div>
                        <div class="form-item row">
                            <div class="label">
                                <label>按钮图标</label>
                            </div>
                            <div class="body">
                                <p class="icon" name="icon"></p>
                            </div>
                        </div>
                        <div class="form-item row">
                            <div class="label">
                                <label>序号</label>
                            </div>
                            <div class="body">
                                <p class="sortNum" name="sortNum"></p>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 添加权限 -->
<div class="popup-default z-popup z-fixed z-df z-flex-cc z-hide">
    <div class="bg" data-popup-close></div>
    <!--添加权限 -->
    <div class="popup-add-auth section z-hide">
        <div class="title">添加权限</div>
        <div class="content" id="authForm">
            <form>
                <div class="form-item row">
                    <div class="label">
                        <label>父级权限ID</label>
                    </div>
                    <div class="body">
                        <input type="text" value="" disabled="disabled" class="parentId" name="parentId">
                        <button class="z-btn z-default select-btn select-auth">选择</button>
                    </div>
                </div>
                <div class="form-item z-hide">
                    <div class="label">
                        <label>权限ID</label>
                    </div>
                    <div class="body">
                        <input type="text" value="" disabled="disabled" class="authorityId" name="authorityId">
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>权限名称</label>
                    </div>
                    <div class="body upload" data-limit="0" data-input-name="" data-data-key="resize">
                        <input type="text" value="" class="authorityName" name="authorityName" data-name="权限名称" data-rule="required,length" minlength="2" maxlength="32">
                    </div>
                </div>

                <div class="form-item row">
                    <div class="label">
                        <label>类型</label>
                    </div>
                    <div class="body upload" data-limit="0" data-input-name="" data-data-key="resize">
                        <select class="type" name="type" data-name="类型" data-rule="required">
                            <option value="1" selected>系统</option>
                            <option value="2">菜单</option>
                            <option value="3">按钮</option>
                        </select>
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>权限描述</label>
                    </div>
                    <div class="body">
                        <textarea rows="10" placeholder="最多输入30字" class="authorityDesc" name="authorityDesc" data-name="权限描述" data-rule="length" maxlength="30"></textarea>
                    </div>
                </div>

                <div class="form-item row">
                    <div class="label">
                        <label>权限标识</label>
                    </div>
                    <div class="body" data-limit="0" data-input-name="" data-data-key="resize">
                        <input placeholder="请输入权限标识" class="sign" name="sign" data-name="权限标识" data-rule="length" maxlength="50">
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>权限路径</label>
                    </div>
                    <div class="body" data-limit="0" data-input-name="">
                        <input placeholder="请输入权限路径" class="url" name="url">
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>按钮CLASS</label>
                    </div>
                    <div class="body" data-limit="0" data-input-name="">
                        <input placeholder="请输入按钮CLASS属性名称" class="classes" name="classes">
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>按钮ID</label>
                    </div>
                    <div class="body" data-limit="0" data-input-name="">
                        <input placeholder="请输入按钮ID属性名称" class="itemId" name="itemId">
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>按钮图标</label>
                    </div>
                    <div class="body" data-limit="0" data-input-name="">
                        <input placeholder="请输入按钮图标" class="icon" name="icon">
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>序号</label>
                    </div>
                    <div class="body" data-limit="0" data-input-name="">
                        <input placeholder="请输入序号" class="sortNum" name="sortNum">
                    </div>
                </div>
            </form>
            <div class="z-btn-group">
                <a class="btn-sub z-btn z-primary auth-comfirm">确定</a>
                <a class="z-btn z-default" data-popup-close>取消</a>
            </div>
        </div>
    </div>
</div>

<div id="rMenu" class="rMenu">
    <ul class="rm-group rmg-1">
        <li id="mAddNode" onclick="addTreeNode('node');" data-addDept>添加子权限</li>
        <li id="mEditNode" onclick="editTreeNode('node');" data-editDept>编辑权限</li>
        <li id="mDel" onclick="removeTreeNode();" data-delDept>删除权限</li>
    </ul>
    <ul class="rm-group rmg-2">
        <li id="mAddRoot" onclick="addTreeNode('root');" data-addDept>添加顶级权限</li>
    </ul>
</div>

<script th:src="@{/lib/jquery.min.js}"></script>
<script th:src="@{/lib/layer-v3.1.1/layer/layer.js}"></script>
<script th:src="@{/js/form.js}"></script>
<script th:src="@{/js/popup.js}"></script>
<script th:src="@{/js/admin/app.js}"></script>
<script th:src="@{/lib/tree/jquery.ztree.core-3.5.js}"></script>
<script th:src="@{/js/tree.js}"></script>

<script>

    // 过滤器 - 从URL加载搜索数据
    $(".filter").formLoad(App.query);

    // 过滤器 - 加载select联动内容
    $('[name="searchType"] option').each(function (index, element) {
        if (element.selected == true) {
            $('.j-option-switch .content').html($(".search").children('div').eq(index).html())
        }
    })

    var zTree = null,
        pageParams = {
            departmentId: '',
            roleId: '',
            search: ''
        },
        OptType = 1,
        authData = null,
        authPanelPicker = '.popup-add-auth';

    var auth = {
        editAuth: false,
        addAuth: false,
        delAuth: false,
        checkAuth: false
    };

    $(function () {

        pageParams = $.extend(true, pageParams, App.pageParams);

        //初始化按钮显示
        auth = $.extend(true, auth, App.initBtnView(top.authBtns || []));


        if (auth['checkAuth']) {
            initTree();

            $('.z-table-con').show();
        } else {
            $('.left-sidebar').html('抱歉，您现在没有查看权限内容的权限');
        }

        if (!auth['addAuth']) {
            $('#mAddNode, #mAddRoot').remove();
        }
        if (!auth['editAuth']) {
            $('#mEditNode').remove();
        }
        if (!auth['delAuth']) {
            $('#mDel').remove();
        }

        eventListen();
    });

    function initTree() {
        // 初始化树结构
        zTree = (new Tree).init({
            async: {
                url: App.apiUrlHost + '/sysAuthority/list',
                dataFilter: filter,
            },
            callback: {
                onRightClick: zTreeOnRightClick,
                onClick: zTreeOnClick
            },
        });
    }

    function eventListen() {
        /*========== 事件监听 ===================================================*/
        // 添加权限-提交
        $("#authForm").form({
            submitSelector: '.auth-comfirm',
            msg: function (msg) {
                popup.tips(msg);
            },
            submit: function () {

                comfirmFun();

            }
        });
        // $('.auth-comfirm').click(() => {
        //     comfirmFun();
        // })

        // 添加权限
        $('.add-auth, .edit-auth').click(function () {

            App.clearForm(authPanelPicker);

            if ($(this).hasClass('edit-auth')) {
                OptType = 2;
                editAuth();
            } else {
                OptType = 1;
                addAuth()
            }
        })

        // 选择权限
        $('.select-auth').click(e => {
            e.preventDefault();
            layerOpen({
                type: 1,
                title: '选择权限',
                url: './selectAuth.html',
                comfirm: (index, layero, layer) => {

                    var $ids = $(layero.find('iframe')).contents().find(".src-ids");

                    var html = $ids.html().replace(/\<br\>/g, ',');
                    // alert('选取的id为：' + html);
                    $('[name=parentId]').val(html);

                    layer.close(index);
                },
                cancel: (index, layero, layer) => {

                    layer.close(index);
                }
            })
        });
    }

    // function openLayer() {
    //     layerOpen({
    //         type: 1,
    //         title: '选择权限',
    //         url: './selectDept.html',
    //         comfirm: (index, layero, layer) => {
    //
    //             var $ids = $(layero.find('iframe')).contents().find(".src-ids");
    //
    //             var html = $ids.html().replace(/\<br\>/g, ',');
    //             // alert('选取的id为：' + html);
    //             $('[name=parentId]').val(html);
    //
    //             layer.close(index);
    //         },
    //         cancel: (index, layero, layer) => {
    //
    //             layer.close(index);
    //         }
    //     })
    // }

    function editAuth() {
        if (!checkSelect()) return;

        var checkResult = zTree.tree.getSelectedNodes();
        // todo 获取需修改的数据
        getAuth(checkResult[0].id, (result) => {

            App.fillForm(authPanelPicker, result);
            $(authPanelPicker + ' .title').html('编辑权限');
            $('.parentId').val(checkResult[0].pId);
        });
        popup.open(authPanelPicker);
    }

    function addAuth() {
        $(authPanelPicker + ' .title').html('添加权限');
        popup.open(authPanelPicker);
    }

    function checkSelect() {
        var checkResult = zTree.tree.getSelectedNodes();

        if (checkResult.length <= 0) {
            popup.tipsTop({type: 'warning', msg: '请选择要修改的权限'})
            return false;
        } else {
            console.log('选择数量检测成功');
            return true;
        }
    }

    function comfirmFun() {
        // 数据整合
        var data = {
            'authorityId': $(authPanelPicker + ' [name=authorityId]').val() || '',
            'parentId': $(authPanelPicker + ' [name=parentId]').val(),
            'type': $(authPanelPicker + ' [name=type]').val(),
            'authorityName': $(authPanelPicker + ' [name=authorityName]').val(),
            'authorityDesc': $(authPanelPicker + ' [name=authorityDesc]').val(),
            'sign': $(authPanelPicker + ' [name=sign]').val(),
            'url': $(authPanelPicker + ' [name=url]').val(),
            'classes': $(authPanelPicker + ' [name=classes]').val(),
            'itemId': $(authPanelPicker + ' [name=itemId]').val(),
            'icon': $(authPanelPicker + ' [name=icon]').val(),
            'sortNum': $(authPanelPicker + ' [name=sortNum]').val() || '',
            'able': 1
        };
        var url = '';

        if (OptType == 1) {
            url = App.apiUrlHost + '/sysAuthority/saveSysAuthority';
            // 添加
            submitData(url, data, (data, result) => {
                // 刷新树节点
                doAddTreeNode({
                    id: result.authorityId,
                    isParent: false,
                    name: result.authorityName,
                    pId: result.parentId
                });
                popup.close(authPanelPicker)
            });
        } else {
            url = App.apiUrlHost + '/sysAuthority/updateSysAuthority';

            authData['parentId'] = $('[name=parentId]').val();

            authData = $.extend(true, authData, data);

            // 修改
            submitData(url, authData, (result) => {
                // 刷新树节点

                replaceTreeNode({
                    id: result.authorityId,
                    name: result.authorityName,
                    pId: result.parentId
                })

                popup.close(authPanelPicker);
                popup.tipsTop({type: 'success', msg: '修改成功'});
            });

        }
    }

    //节点右击
    function zTreeOnRightClick(event, treeId, treeNode) {
        if (!treeNode && event.target.tagName.toLowerCase() != 'button' && $(event.target).parents('a').length == 0) {
            zTree.tree.cancelSelectedNode();
            zTree.showRMenu('root', event.clientX, event.clientY);
        } else if (treeNode && !treeNode.noR) {
            zTree.tree.selectNode(treeNode);
            zTree.showRMenu('node', event.clientX, event.clientY);
        }
    }

    // 树节点被点击事件
    function zTreeOnClick(event, treeId, treeNode) {

        var treeNodeID = treeNode.id;

        // 叶子节点，刷新列表数据
        getAuth(treeNodeID, (result) => {

            App.fillForm('.z-table-con', result)
        });
    }

    // 获取到树结构时对数据进行处理
    function filter(treeId, parentNode, data) {

        console.log('过滤数据');
        if (data.code == 0) {

            data.data = JSON.parse(JSON.stringify(data.data).replace(/parentId/g, 'pId'));
            data.data = JSON.parse(JSON.stringify(data.data).replace(/authorityId/g, 'id'));
            data.data = JSON.parse(JSON.stringify(data.data).replace(/authorityName/g, 'name'));
            data.data = JSON.parse(JSON.stringify(data.data).replace(/url/g, 'href'));
            data.data = JSON.parse(JSON.stringify(data.data).replace(/icon/g, 'iconimg'));

            var childNodes = data.data;

            return childNodes;
        } else {

            return null;
        }

    }

    // 右键菜单添加字节点
    function addTreeNode(type) {
        zTree.hideRMenu();

        OptType = 1;

        var nodes = zTree.tree.getSelectedNodes();

        var title = type === 'root' ? '添加根权限' : '添加子权限',
            pid = (nodes && nodes.length && type === 'node') ? nodes[0].id : '',
            pname = (nodes && nodes.length && type === 'node') ? nodes[0].name : 'ROOT';

        App.clearForm(authPanelPicker);
        $(authPanelPicker + ' .title').html(title);
        $('.parentId').val(pid);
        popup.open(authPanelPicker);

    }

    function doAddTreeNode(newNode) {
        zTree.hideRMenu();
        if (zTree.tree.getSelectedNodes() && zTree.tree.getSelectedNodes().length > 0) {
            newNode.checked = zTree.tree.getSelectedNodes()[0].checked;
            zTree.tree.addNodes(zTree.tree.getSelectedNodes()[0], newNode);
        } else {
            zTree.tree.addNodes(null, newNode);
        }
    }

    // 右键菜单编辑节点
    function editTreeNode() {

        OptType = 2;

        zTree.hideRMenu();
        var nodes = zTree.tree.getSelectedNodes();
        if (nodes && nodes.length > 0) {
            var id = nodes[0].id,
                pId = nodes[0].pId;

            getAuth(id, (result) => {
                App.fillForm(authPanelPicker, result);
                $(authPanelPicker + ' .title').html('编辑部门');
                $('.parentId').val(pId);
                popup.open(authPanelPicker);
            })

        }
    }

    // 替换节点
    function replaceTreeNode(newNode) {
        //获取当前节点
        zTree.tree.getSelectedNodes()[0].name = newNode.name;
        zTree.tree.getSelectedNodes()[0].id = newNode.id;
        zTree.tree.getSelectedNodes()[0].pId = newNode.pId;
        zTree.tree.updateNode(zTree.tree.getSelectedNodes()[0])
    }

    // 删除节点
    function removeTreeNode() {
        zTree.hideRMenu();
        var nodes = zTree.tree.getSelectedNodes();
        if (nodes && nodes.length > 0) {
            if (nodes[0].children && nodes[0].children.length > 0) {
                var msg = '要删除的节点是父节点，如果删除将连同子节点一起删掉。\n\n请确认！';
                if (confirm(msg) == true) {
                    doDelNode(nodes[0].id, function () {
                        zTree.tree.removeNode(nodes[0]);
                    });

                }
            } else {
                doDelNode(nodes[0].id, function () {
                    zTree.tree.removeNode(nodes[0]);
                });
            }
        }
    }


    /**========= 接口操作=====================================*/

    function doDelNode(id, callback) {
        App.getData({
            url: App.apiUrlHost + '/sysAuthority/deleteSysAuthority',
            data: {authorityId: id},
            success: function (result) {

                if (callback && typeof callback === 'function') {
                    if (result.code == 0) {
                        callback(result);
                    } else {
                        popup.tipsTop({type: 'error', msg: result.msg})
                    }
                }
            }
        });
    }


    function getAuth(id, callback) {
        App.getData({
            url: App.apiUrlHost + '/sysAuthority/getById',
            data: {authorityId: parseInt(id, 10)},
            success: function (result) {

                if (result.code == 0 && callback && typeof callback == 'function') {
                    authData = result.data;
                    callback(result.data);
                } else {
                    popup.tipsTop({type: 'error', msg: result.msg})
                }
            }
        })
    }

    function submitData(url, data, callback) {
        App.getData({
            url: url,
            data: data,
            success: function (result) {

                if (result.code == 0 && callback && typeof callback == 'function') {
                    callback(data, result.data);
                } else {
                    popup.tipsTop({type: 'error', msg: result.msg})
                }
            }
        })
    }
</script>
<script th:src="@{/lib/flatpickr/flatpickr.js}"></script>
<script th:src="@{/lib/flatpickr/zh.js}"></script>
<script>
    flatpickr.localize(flatpickr.l10ns.zh); // 设置为中文
    flatpickr(".flatpickr-hour", {
        enableTime: true,
        noCalendar: true,
        dateFormat: "H:i",
        time_24hr: true
    });
</script>
</body>

</html>